package cn.dyp.com.agriculture.activity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;

import cn.dyp.com.agriculture.R;
import cn.dyp.com.agriculture.dialog.IPSetDialog;
import cn.dyp.com.agriculture.dialog.RegisterDialog;
import cn.dyp.com.agriculture.request.BaseRequest;
import cn.dyp.com.agriculture.request.LoginRequest;
import cn.dyp.com.agriculture.request.RequestThread;

/**
 * Created by C515 on 2017/5/5.
 */
public class LoginActivity extends BaseActivity{
    private TextView ip_set;
    private EditText username_et,password_et;
    private Button login_button,register_button;
    private CheckBox password_hide,password_save;
    private RequestThread mThread;
    private LoginRequest mRequest;
    private ProgressDialog mDialog;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login_layout);
        init();
        setListener();
        setText();
        setRequest();
    }

    /**
     * 设置请求对象
     *
     */
    private void setRequest() {   //mRequest是LoginRequest
        mRequest = new LoginRequest("");
        mRequest.setOnResponseEventListener(new BaseRequest.OnResponseEventListener() {
            @Override
            public void onResponse(BaseRequest request, BaseRequest.RequestResult result) {
                mDialog.dismiss();
                if (mRequest.isSuccess()) {
                    Intent mIntent = new Intent(LoginActivity.this,
                            MainActivity.class);
                    startActivity(mIntent);
                    LoginActivity.this.finish();
                } else {
                    showAlertDialog(getString(R.string.prompt), getString(R.string.login_failed));
                }
            }
        });
    }

    /**
     * 启动网络连接线程
     */
    private void setThread() {
        if (mRequest != null) {
            mThread = new RequestThread(this, mApp.getHandler());
            mThread.setRequest(mRequest);
            mThread.start();
        }
    }

    //控件实例化
    private void init(){
        ip_set=(TextView) findViewById(R.id.ip_set);
        username_et=(EditText) findViewById(R.id.username_et);
        password_et=(EditText) findViewById(R.id.password_et);
        login_button=(Button) findViewById(R.id.login_button);
        register_button=(Button) findViewById(R.id.register_button);
        password_hide=(CheckBox) findViewById(R.id.password_hide);
        password_save=(CheckBox) findViewById(R.id.password_save);
        mDialog = new ProgressDialog(this);
        username_et.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    private void setText() {
        username_et.setText(mApp.getUsername());
    }

    //用匿名类的方式注册监听器
    private void setListener() {
        ip_set.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view) {
                IPSetDialog dialog = new IPSetDialog(LoginActivity.this);//传入上下文
                dialog.show(getFragmentManager(), "dialog");
            }
        });

        login_button.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view) {
                userLogin();
                setThread();
            }
        });

        register_button.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view) {
                RegisterDialog dialog = new RegisterDialog(LoginActivity.this);//传入上下文
                dialog.show(getFragmentManager(), "dialog");
            }
        });
        password_hide.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener(){
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if(isChecked){
                    //如果选中，显示密码
                    password_et.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                }else{
                    //否则隐藏密码
                    password_et.setTransformationMethod(PasswordTransformationMethod.getInstance());
                }
            }
        });
        password_save.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener(){
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if(isChecked){
                    //如果选中，保存密码
                }else{
                    //否则不保存
                }
            }
        });

    }

    //用户登录限制
    private void userLogin(){
        String userName = username_et.getText().toString().trim();//获得对象内容，转成string类型，去掉前后空白
        String password = password_et.getText().toString().trim();
        if (userName.equals("")) {
            showAlertDialog(getString(R.string.prompt), getString(R.string.username_not_empty));//提示框
            return;   //中止当前函数的运行
        }
        if (password.equals("")) {
            showAlertDialog(getString(R.string.prompt), getString(R.string.password_not_empty));
            return;
        }
        mApp.setUsername(userName);
        mRequest.setUserName(userName);
        mRequest.setPassword(password);
        setLoadingDialog();
    }

    /**
     * 设置加载Dialog
     */
    private void setLoadingDialog() {
        mDialog.setMessage(getString(R.string.login_wait));
        mDialog.setCanceledOnTouchOutside(false);
        mDialog.setIndeterminate(false);
        mDialog.setCancelable(true);
        mDialog.show();
    }

    /**
     * 显示提示对话框
     * title 对话框标题
     * message 对话框内容
     */
    protected void showAlertDialog(String title, String message) {
        AlertDialog.Builder dialog= new AlertDialog.Builder(this);
        dialog.setTitle(title);
        dialog.setMessage(message);
        dialog.setPositiveButton(getString(android.R.string.ok), null);//设置确认按钮的文字，但是不添加监听
        dialog.show();
    }
}
